package logic

import (
	"cart_srv/model/mysql"
	"cart_srv/model/redis"
	"context"

	"cart_srv/internal/svc"
	"cart_srv/pb/cart"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	o := mysql.Goods{}
	err := o.FindGoods(in.GoodsId)
	if err != nil {
		logx.Error("商品查询失败")
		return nil, err
	}
	if o.ID == 0 {
		logx.Error("商品不存在")
		return nil, err
	}

	stock := redis.GetGoodsStock(in.GoodsId)
	if stock < in.Num {
		logx.Error("库存不足")
		return nil, err
	}

	if redis.GetExist(in.UserId, in.GoodsId) {
		logx.Error("商品已存在")
		err = redis.UpdateCart(in.UserId, in.GoodsId, in.Num)
		if err != nil {
			logx.Error("修改失败")
			return nil, err
		}
	} else {
		goods := map[string]interface{}{
			"user_id":     in.UserId,
			"goods_id":    in.GoodsId,
			"num":         in.Num,
			"goods_title": o.GoodsTitle,
			"goods_cover": o.GoodsCover,
			"goods_price": o.GoodsPrice,
			"checked":     1,
		}

		err = redis.AddCart(in.UserId, in.GoodsId, goods)
		if err != nil {
			logx.Error("添加失败")
			return nil, err
		}
	}

	return &cart.AddCartResponse{Success: true}, nil
}
